package gps.map.test;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem; 

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
 

//Internet conection alert in main activity

//BUT FIRST +_+ optimize the GODDAMN CODE!


public class GPSMapActivity extends MapActivity 
{    
		//Variables
		
		public GeoPoint p;
		public MapView mapview;

		private boolean gps_enabled=false;
		private boolean network_enabled=false;
	    public EditText txted = null;
	    public MyItemizedOverlay itemizedoverlay;
	    public List<Overlay> mapOverlays;
	    public OverlayItem [] overlayitem = new OverlayItem[5] ;
		public MyLocationOverlay myLoc;
		private static MapController mc = null;
		private static LocationManager lm;
		private static Location loc;
		private static String provider;
		private static double lat;
		private static double lon;
		private Thread thr;
		private Road mRoad;
		
		
	    /** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState)
	    {
	    	

	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	    	//Variables
	        //Provider
	        provider = LocationManager.GPS_PROVIDER;
	        //MapView
	        mapview = (MapView) findViewById(R.id.mapView);
	        //Enable Zoom on map
	        mapview.setBuiltInZoomControls(true);
	        //MapView Controller
	        mc=mapview.getController();
	        txted = (EditText) findViewById(R.id.id1);
	        //My current location
	        myLoc=new MyLocationOverlay(this, mapview);
	        mapOverlays = mapview.getOverlays();
	        //Drawable resource for bus stops
	        Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
	        //Itemized Overlay used to draw on map
	        itemizedoverlay = new MyItemizedOverlay(drawable,this);
	        //Location manager, to get current location
	        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	        //Display my location
	        mapOverlays.add(myLoc);
	        myLoc.enableCompass();
	        myLoc.enableMyLocation();
	    	mc.setZoom(16);
	    	
	        //test geopoint
	    	p=new GeoPoint(60982617,25661400);
	    	
	    	drawBusStops(p);

	    	//get last known location - must be replaced by main menu code   	
			loc =lm.getLastKnownLocation(provider);
	    	if(loc != null){
	    		lat = loc.getLatitude();
	   	    	lon = loc.getLongitude();
	   	    	txted.setText(""+lat+"    "+lon);
	    	}
	    	
	    	//Thread for drawing path
			thr=new Thread() {
				@Override
				public void run() {
					double fromLat = lat, fromLon = lon, toLat = p.getLatitudeE6()/1E6, toLon = p.getLongitudeE6()/1E6;
					String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
					InputStream is = getConnection(url);
					mRoad = RoadProvider.getRoute(is);
					mHandler.sendEmptyMessage(0);
				}
			};
	    }
	
	
	    
	    //Method to draw Bus Stops on map 
	    public void drawBusStops(GeoPoint p)
	    {
	    	overlayitem[1] = new OverlayItem(p, "Bus Stop", "This is one of the available bus stops.");
	        itemizedoverlay.addOverlay(overlayitem[1]);
	        mapOverlays.add(itemizedoverlay);
	    }
	    
	    //enable GPS alert
	    
	    private void createGpsDisabledAlert() {
	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder
	                .setMessage(
	                        "Your GPS is disabled! Would you like to enable it?")
	                .setCancelable(false).setPositiveButton("Enable GPS",
	                        new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int id) {
	                                showGpsOptions();
	                            }
	                        });
	        builder.setNegativeButton("Do nothing",
	                new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int id) {
	                        dialog.cancel();
	                    }
	                });
	        AlertDialog alert = builder.create();
	        alert.show();
	    }
	    
	    
	    //show GPS menu screen
	    private void showGpsOptions() {
	        Intent gpsOptionsIntent = new Intent(
	                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	        startActivity(gpsOptionsIntent);
	    } 
	    
	    //Method to determine phone location and center map on that location
	    public static void centerOnLocation() {
			loc =lm.getLastKnownLocation(provider);
	    	if(loc != null){
	    		lat = loc.getLatitude();
	   	    	lon = loc.getLongitude();
	   	    	
		    	GeoPoint newPoint = new GeoPoint((int)(lat*1e6),(int)(lon*1e6)); 	   
		    	mc.animateTo(newPoint);
		    	}
	    	}   
	      
	    @Override
	    protected boolean isRouteDisplayed() {
	        return false;
	    }
	    
	    
	    //On resume event
	    
	    public void onResume() {
	    	super.onResume();
	         
	        myLoc.enableCompass();
	        myLoc.enableMyLocation();
	        //Check GPS & Network Connection availability
	    	try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
	    	try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
	    	if(network_enabled)
	    		//thread will only run if Network Connection is enabled, for data transfer, to get route
	    		try{
	    			thr.run();
	    		}
	    		catch(Exception e){}
	    	//verify if GPS is enabled,if not start alert
	        if (!gps_enabled) {
	            		createGpsDisabledAlert();
	        } else {
	            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1.0f, new geoUpdateHandler());
	
	        }
	    }
	
	
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			MapOverlay mapOverlay = new MapOverlay(mRoad, mapview);
			List<Overlay> listOfOverlays = mapview.getOverlays();
			listOfOverlays.clear();
			listOfOverlays.add(mapOverlay);
			listOfOverlays.add(myLoc);
			drawBusStops(p);
			mapview.invalidate();
		};
		
	};
	//Input stream for establishing connection to URL
	private InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
	
	
	class MapOverlay extends com.google.android.maps.Overlay {
		Road mRoad;
		ArrayList<GeoPoint> mPoints;
		//create the array of GeoPoints 	
		public MapOverlay(Road road, MapView mv) {
			mRoad = road;
			if (road.mRoute.length > 0) {
				mPoints = new ArrayList<GeoPoint>();
				for (int i = 0; i < road.mRoute.length; i++) {
					mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
							(int) (road.mRoute[i][0] * 1000000)));
				}
			}
		}
		//Draw Path
		@Override
		public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
			super.draw(canvas, mv, shadow);
			try {
			drawPath(mv, canvas);
			}
			catch (Exception e)
			{
				Log.d("Drawing", e.toString());
			}
			return true;
		}
	
		public void drawPath(MapView mv, Canvas canvas) {
			int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
			Paint paint = new Paint();
			paint.setColor(Color.GREEN);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(7);
			for (int i = 0; i < mPoints.size(); i++) {
				Point point = new Point();
				mv.getProjection().toPixels(mPoints.get(i), point);
				x2 = point.x;
				y2 = point.y;
				if (i > 0) {
					canvas.drawLine(x1, y1, x2, y2, paint);
				}
				x1 = x2;
				y1 = y2;
				}
		}
	}
}

